package inits

import (
	"app-webapi/comm/g"
	"app-webapi/service"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"math"
	"math/rand"
	"strconv"
	"time"
)

func Mqtt() {
	// 初始化mqtt客户端
	broker := initMqttBroker()
	g.MqttClient = broker

}

//SubscribeMqtt 订阅MQTT
func SubscribeMqtt() {
	// 订阅告警事件
	service.TestMqttEvent()
}

func initMqttBroker() mqtt.Client {
	//配置
	clientId := "mqtt" + strconv.FormatInt(rand.Int63n(math.MaxInt64), 16)
	server := "tcp://local-gateway-host:1883"
	clientOptions := mqtt.NewClientOptions().AddBroker(server).SetClientID(clientId).SetCleanSession(true)
	clientOptions.SetAutoReconnect(true)
	clientOptions.SetMaxReconnectInterval(5 * time.Second)
	clientOptions.SetOnConnectHandler(func(client mqtt.Client) {
		g.Logger.Info("mqtt连接成功")
		SubscribeMqtt()
	})
	//log.Printf("初始化mqtt配置 clientId: %s, address: %s, upDataTopic: %s, downDataTopic: %s", clientId, server, upDataTopic, downDataTopic)
	//连接
	client := mqtt.NewClient(clientOptions)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		return initMqttBroker()
	}
	return client
}
